package com.example.baiguangsystem.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.baiguangsystem.vo.ResultType;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * 操作检查拦截器，只有登录过了之后才可以进行操作
 *
 * @Author: 27641
 * @ProjectName: BaiGuangSystem
 * @Date: 2022/02/06/19:07
 * @noinspection SpellCheckingInspection
 */
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    /**
     * 检查用户是否完成了登录
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        HttpSession session = request.getSession();
        /*获取所有cookie*/
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                Object attribute = session.getAttribute(cookie.getName());
                if (attribute != null) {
                    return true;
                }
            }
        }
        ResultType<?> fail = ResultType.fail("你还没有进行登录，需要先进性登录!");
        sendHintMessages(response, fail);
        return false;
    }


    /**
     * 提示客户端没有权限操作，需要先进行登录
     *
     * @param response      响应对象
     * @param resultMessage 提示信息封装对象
     */
    @SneakyThrows
    public static void sendHintMessages(HttpServletResponse response, ResultType resultMessage) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        String jsonString = JSON.toJSONString(resultMessage);
        writer.println(jsonString);
        writer.flush();
        writer.close();
    }
}
